import Koa from "koa";
import Router from "koa-router";
import fs from "fs/promises";
import path from "path";
import axios from "axios";
import { optimize } from "svgo";
import svgs2SymbolFile from "./svg2Symbol.js";

const app = new Koa();
const router = new Router();
const bandPrefix = "./public/icon";

const svgoPipe = async (fileStr) => {
  const configStr = await fs.readFile("./svgo.config.json");
  const config = JSON.parse(configStr || "{}");
  const res = optimize(fileStr, config);
  return res.data;
};

router.get("/api/bands", async (ctx) => {
  const bands = await fs.readdir(bandPrefix);
  const res = [];
  const pAll = Promise.all(
    bands.map(async (bandName) => {
      const iconPrefix = path.join(bandPrefix, bandName);
      const files = await fs.readdir(iconPrefix);
      res.push({
        name: bandName,
        icons: files.slice(0, 12).map((fileName) => ({
          name: fileName.replace(".svg", ""),
          url: path.join(iconPrefix, fileName),
        })),
      });
    })
  );
  await pAll;
  ctx.body = JSON.stringify({
    code: 200,
    data: res,
  });
});

router.get("/api/icons", async (ctx) => {
  if (!ctx.query.band) {
    ctx.status = 404;
    return;
  }
  const iconPrefix = path.join(bandPrefix, ctx.query.band);

  const files = await fs.readdir(iconPrefix);

  const icons = files.map((fileName) => ({
    name: fileName.replace(".svg", ""),
    url: path.join(iconPrefix, fileName),
  }));
  ctx.body = JSON.stringify({
    code: 200,
    data: icons,
  });
});

router.post("/api/svgPipe", async (ctx) => {
  const svgText = await new Promise((resolve) => {
    let text = "";
    ctx.req.on("data", (t) => {
      text += t;
    });
    ctx.req.addListener("end", () => {
      resolve(text);
    });
  });
  ctx.body = await svgoPipe(svgText);
});

const downloadFile = async (url, fileName, filePath) => {
  const res = await axios(url);
  await fs.writeFile(path.join(bandPrefix, filePath, fileName), res.data);
};

router.post("/api/downloadBand", async (ctx) => {
  const bodyStr = await new Promise((resolve) => {
    let text = "";
    ctx.req.on("data", (t) => {
      text += t;
    });
    ctx.req.addListener("end", () => {
      resolve(text);
    });
  });
  const { bandName, icons } = JSON.parse(bodyStr || "{}");
  const dirPath = path.join(bandPrefix, bandName);
  try {
    await fs.stat(dirPath);
  } catch {
    const recur = await fs.mkdir(dirPath, { recursive: true });
    console.log("create dir", recur);
  }

  const pAll = Promise.all(
    icons.map((icon) => downloadFile(icon.url, icon.name, bandName))
  );
  await pAll;
  ctx.body = "success";
});

router.get("/api/generateBand", async (ctx) => {
  const { band } = ctx.query;
  const symbols = svgs2SymbolFile(path.join(bandPrefix, band));
  const boundjs = `(function(window){var svgSprite='<svg>${symbols.join(
    ""
  )}</svg>';var script=function(){var scripts=document.getElementsByTagName("script");return scripts[scripts.length-1]}();var shouldInjectCss=script.getAttribute("data-injectcss");var ready=function(fn){if(document.addEventListener){if(~["complete","loaded","interactive"].indexOf(document.readyState)){setTimeout(fn,0)}else{var loadFn=function(){document.removeEventListener("DOMContentLoaded",loadFn,false);fn()};document.addEventListener("DOMContentLoaded",loadFn,false)}}else if(document.attachEvent){IEContentLoaded(window,fn)}function IEContentLoaded(w,fn){var d=w.document,done=false,init=function(){if(!done){done=true;fn()}};var polling=function(){try{d.documentElement.doScroll("left")}catch(e){setTimeout(polling,50);return}init()};polling();d.onreadystatechange=function(){if(d.readyState=="complete"){d.onreadystatechange=null;init()}}}};var before=function(el,target){target.parentNode.insertBefore(el,target)};var prepend=function(el,target){if(target.firstChild){before(el,target.firstChild)}else{target.appendChild(el)}};function appendSvg(){var div,svg;div=document.createElement("div");div.innerHTML=svgSprite;svgSprite=null;svg=div.getElementsByTagName("svg")[0];if(svg){svg.setAttribute("aria-hidden","true");svg.style.position="absolute";svg.style.width=0;svg.style.height=0;svg.style.overflow="hidden";prepend(svg,document.body)}}if(shouldInjectCss&&!window.__iconfont__svg__cssinject__){window.__iconfont__svg__cssinject__=true;try{document.write("<style>.svgfont {display: inline-block;width: 1em;height: 1em;fill: currentColor;vertical-align: -0.1em;font-size:16px;}</style>")}catch(e){console&&console.log(e)}}ready(appendSvg)})(window)`;
  ctx.set("content-type", "application/javascript");
  ctx.body = boundjs;
});

app.use(router.routes());

app.listen(3001, () => console.log("server started"));
